/*
 *  Copyright 2010 Alexey Frishman (alexey.frishman@gmail.com)
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may not
 *  use this file except in compliance with the License. You may obtain a copy of
 *  the License at
 *  
 *  http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 *  License for the specific language governing permissions and limitations under
 *  the License.
 * 
 */

package org.json4g.serialization;

import com.google.gwt.json.client.JSONNull;
import com.google.gwt.json.client.JSONValue;
import com.gwtent.reflection.client.Field;

/**
 * Be careful to place this serializer after all primitive serializers, especially after String serializer, because this one handles
 * empty strings as nulls
 */
public class JsonNullSerializer implements JsonSerializer {

    /**
     * Always returns null
     */
    @Override
    public Object deserialize(JSONValue json, Field field) {
        return null;
    }

    /**
     * Always serializes as undefined in JSON (value/field is not included at all)
     */
    @Override
    public JSONValue serialize(Object object) {
        return JSONNull.getInstance();
    }

    /**
     * Supports only null values.
     */
    @Override
    public boolean supports(Object object) {
        return object == null;
    }

    /**
     * Supports nulls and empty strings from JSON. They will be mapped as null values in Java.
     * It does NOT guarantee that value should really be null in Java in case if it's an empty string in JSON.
     */
    @Override
    public boolean supports(JSONValue json, Field field) {
        // If we are here, then there is some value in JSON, which is null.
        // Otherwise the field itself would be absent in JSON and we would not get here at all
        return json != null && (json.isNull() != null || json.isString() != null && (json.toString().equals("\"\"") || json.toString().equals("''")));
    }
    
    
}
